/* turtle.mly */

%{
  open Printf
  
  (* Pi value *)
  let pi = 4.0 *. atan 1.0

  (* List of turtle states.
     A state is a 3-tuple,composed by an angle in radian, an abscissa 
     and an ordinate. It's corresponding to the turtle's position.
     The head of the list is the actual state of the turtle
  *)
  let turtle_states = ref [((pi/.2.), 0., 0.)]

  let move_fun k =
    match !turtle_states with
  	[]         -> 
	  failwith "turtle is not initialized"
      |	(a,x,y)::_ -> 
	turtle_states := (a, (x +. k *. (cos a) ), (y+.k*.(sin a)))::!turtle_states
	
  let turn_fun d =
    match !turtle_states with
  	[]         -> 
	  failwith "turtle is not initialized"
      |	(a,x,y)::_ -> 
	turtle_states := (a+.d*.(pi/.180.), x, y)::!turtle_states

  let current_state () =
    match !turtle_states with
  	[]   -> 
	  failwith "turtle is not initialized"
      |	c::_ -> c
%}

%token <float> NUM
%token NEWLINE SEMICOLON LEFTBRACKET RIGHTBRACKET
%token MOVETOK TURNTOK

%start prog
%type <unit> prog

/* Grammar rules and actions follow */
%% 
prog: LEFTBRACKET /* empty */ RIGHTBRACKET  { }
| LEFTBRACKET cmds RIGHTBRACKET	{ }
  ;

cmds:	cmd		        { }
| cmd SEMICOLON cmds	        { }
  ;


cmd:    
  MOVETOK NUM                 
  { 
    print_endline ("move "^(string_of_float $2));
    move_fun $2
  }
| TURNTOK NUM                   
  { 
    (* print_endline ("turn "^(string_of_float $2)) *)
    turn_fun $2
  }
      
%%

